package demo4.controller;

import demo4.mapper.IUserMapper;
import demo4.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Scanner;

/**
 * Controller 控制器层  将来这个层级中的类主要负责和用户打交道
 * 后面学习Spring MVC时会介绍，中MVC中的C指的就是Controller
 */
@Component
public class UserController {
    @Autowired
    private IUserMapper userMapper;

    public void start() {
        System.out.println("用户系统");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要操作的序号:");
        System.out.println("1.注册");
        System.out.println("2.登录");
        System.out.println("3.修改密码");
        System.out.println("4.用户列表");
//        System.out.println("5. ...");
        int num = scanner.nextInt();
        switch (num) {
            case 1:
                userReg();
                break;
            case 2:
                userLogin();
                break;
            case 3:
                System.out.println("修改密码");
                break;
            case 4:
                System.out.println("用户列表");
                break;
        }
    }

    /**
     * 用户登录处理
     */
    private void userLogin() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("欢迎登录");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        //根据用户名查询该用户注册时的信息
        User user = userMapper.selectByUsername(username);
        if (user != null) {
            if (user.getPassword().equals(password)) {
                System.out.println("登录成功，欢迎【" + user.getNickname() + "】回来");
            } else {
                System.out.println("密码错误");
            }
        } else {
            System.out.println("用户不存在");
        }
    }

    /**
     * 用户注册处理
     */
    private void userReg() {
        System.out.println("欢迎注册");
        User user = new User();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            if (userMapper.selectByUsername(username) == null) {
                user.setUsername(username);
                break;
            }
            System.out.println("用户名已存在");
        }
        System.out.println("请输入密码:");
        user.setPassword(scanner.nextLine());
        System.out.println("请输入昵称:");
        user.setNickname(scanner.nextLine());
        System.out.println("请输入年龄:");
        user.setAge(scanner.nextInt());

        //实际在这里还要进行必要的验证，比如:有没有没输入的，有没有不合法的，是否重复用户

        int num = userMapper.insert(user);
        System.out.println(num > 0 ? "注册成功" : "注册失败");

        System.out.println("UserController:注册完毕");
    }
}










